import user from "@src/models/user";
import jurisdiction from "@src/models/jurisdiction";
import {getID, getMeta, tick} from "@src/util/util";
import moment from "moment";
import {Op} from "sequelize";
import fieldCategory from "@src/models/fieldCategory";


export interface IUser {
    id: string,
    username: string,
    password?: string,
    jurisdictions: Array<{
        id: string,
        name: string,
        english_name: string
    }>,
    lasted_at: string,
    created_at: string,
    updated_at: string
}

export interface jurisdictionsType {
    id: string,
    english_name: string,
    name: string
}

//获取单个用户
export const findUserOne = async (username: string) => {
    return await user.findOne({
        where: {
            username,
        },
    });
};

// 新登录用户设置token
export const updateToken = async (username: string, token: string) => {
    return await user.update({
        token,
        lasted_at: moment().format("X"),
    }, {where: {username}});
};

// 当前用户是否存在
export const isUser = async (username: string) => {
    return await user.count({
        where: {
            username,
        },
    });
};

// 新增用户
export const addUserSql = async (username: string, password: string, jurisdictions: any, time: string) => {
    await user.create({
        id: getID(),
        username,
        password,
        jurisdictions,
        created_at: time,
        updated_at: time,
    });
};

// 查找当前用户信息
export const findUserInfo = async (id: string) => {
    return user.findOne({where: {id}});
};

// 更新用户
export const updateUserSql = async (id: string, username: string, jurisdictions_ids: jurisdictionsType[]) => {
    // 查询需要更新的权限
    const jurisdictionsData = await jurisdiction.findAll({
        attributes: ['id', "name", "english_name"],
        where: {
            id: jurisdictions_ids,
        },
    });
    await user.update({
        username,
        jurisdictions: jurisdictionsData,
        updated_at: moment().format("X"),
    }, {
        where: {
            id,
        },
    });
};

// 刪除用戶
export const delUserSql = async (id: string) => {
    await user.destroy({
        where: {
            id,
        },
    });
};

// 用户列表
export const userListSql = async (offset: number, limit: number, filters: { username?: string | undefined }) => {
    // 条件判断
    const whereObj: any = {};
    for (const v in filters) {
        if (v === "username" && filters[v]) {
            whereObj[v] = {
                [Op.substring]: filters[v],
            };
        }
    }
    const {count, rows} = await user.findAndCountAll(
        {
            attributes: ["id", "username", "jurisdictions", "created_at"],
            where: whereObj,
            // 从第几条开始
            offset,
            //返回多少条
            limit,
            order: [["created_at", "DESC"]],
        },
    );
    return {
        count,
        rows,
    };
};

// 权限初始化
export const qx = async () => {
    const data = [
        {
            name: "文献管理",
            englishName: "literature",
        },
        {
            name: "文章管理",
            englishName: "article",
        },
        {
            name: "区域管理",
            englishName: "region",
        },
        {
            name: "用户管理",
            englishName: "user",
        },
        {
            name: "角色管理",
            englishName: "role",
        },
        {
            name: "数据字典",
            englishName: "dict",
        },
    ].map((v) => {
            return {
                id: getID(),
                name: v.name,
                englishName: v.englishName,
                created_at: parseInt(moment().format("X")),
                updated_at: parseInt(moment().format("X")),
            };
        },
    );
    return await jurisdiction.bulkCreate(data);
};

//权限列表
export const findJurisdictionAll = async () => {
    return await jurisdiction.findAll();
};

//分类生成
export const addCategorySql = async () => {
    const data = ["文献管理"].map(v => {
        return {
            id: getID(),
            name: v,
            created_at: moment().format("X"),
            updated_at: moment().format("X"),
        };
    });
    return await fieldCategory.bulkCreate(data);
};

//分类获取
export const categoryListSql = async () => {
    return await fieldCategory.findAll();
};